const fs = require('fs');
const path = require('path');
const router = require('koa-router')();

router.prefix('/api/data');

router.get('/:fileName', async (ctx, next) => {
  let root = ctx.rootPath;
  let fileName = ctx.params.fileName || '1';

  if (fileName.indexOf('.') == -1) {
    fileName = fileName + '.json';
  }

  let filePath = path.resolve(root, 'datas', 'files', fileName);

  if (!fs.existsSync(filePath)) {
    await (ctx.body = { message: `[${filePath}]文件不存在！` });

    return;
  }

  let stream = fs.createReadStream(filePath);

  await (ctx.body = stream);
});

module.exports = router;